<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus10.html">Previous Chapter</a>
    <li> <a href="cplusplus12.html">Next Chapter</a>
</ul>
<hr>
<a name="Friends"></a><a name="l169"></a>
<h1>Chapter 11: Friends</h1>
<a name="friends"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="friends/intro"></a>In all examples we've discussed up to now, we've seen that <code>private</code>
members are only accessible by the members of their class. This is <em>good</em>, as
it enforces the principles of <a name="an1358"></a>
encapsulation and <a name="an1359"></a>
data hiding: By
encapsulating the data in an object we can prevent that code external to
classes becomes <a name="an1360"></a>
implementation dependent on the data in a class, and by
hiding the data from external code we can control modifications of the data,
helping us to maintain <a name="an1361"></a>
data integrity.
<p>
In this short chapter we will introduce the <a name="an1362"></a>
<code>friend</code> keyword as a means to
allow external functions to access the <code>private</code>
members of a class. In this chapter the subject of
    <a name="an1363"></a>
friendship among classes is not discussed. Situations in which it is
natural to use friendship among classes are discussed in chapters
<a href="cplusplus16.html#NESTEDCLASSES">16</a> and <a href="cplusplus18.html#TEMPLATES">18</a>.
<p>
Friendship (i.e., using the <code>friend</code> keyword) is a complex and dangerous
topic for various reasons:
    <ul>
    <li> Friendship, when applied to program design, is an
        <a name="an1364"></a>
<em>escape mechanism</em> allowing us to circumvent the principles of
encapsulation and data hiding. The use of friends should therefore be
<em>minimized</em> to situations where they can be used naturally.
    <li> If friends are used, realize that friend functions or classes become
<a name="an1365"></a>
implementation dependent on the classes declaring them as friends. Once the
internal organization of the data of a class declaring friends changes, all
its friends must be recompiled (and possibly modified) as well.
    <li> Therefore, as a <a name="an1366"></a>
rule of thumb: <em>don't</em> use friend functions or
classes.
    </ul>
    Nevertheless, there are situations where the <code>friend</code> keyword can be
used quite safely and naturally. It is the purpose of this chapter to
introduce the required syntax and to develop principles allowing us to
recognize cases where the <code>friend</code> keyword can be used with very little
danger.
<p>
Let's consider a situation where it would be nice for an existing class to
have access to another class.  Such a situation might occur when we would like
to give a class developed <em>earlier</em> in history access to a class developed
<em>later</em> in history.
<p>
Unfortunately, while developing the older class, it was not yet known that the
newer class would be developed. Consequently, no provisions were offered in
the older class to access the information in the newer class.
<p>
Consider the following situation.  The <a name="an1367"></a>
insertion operator may be used to
insert information into a stream.  This operator can be given data of several
types: <code>int, double, char *</code>, etc.. Earlier (chapter <a href="cplusplus07.html#MEMORY">7</a>), we
introduced the class <code>Person</code>. The class <code>Person</code> has members to retrieve
the data stored in the <code>Person</code> object, like <code>char const
*Person::name()</code>. These members could be used to `insert' a <code>Person</code>
object into a stream, as shown in section <a href="cplusplus09.html#EXTRACTORS">9.2</a>.
<p>
With the <code>Person</code> class the implementation of the insertion
and extraction operators is fairly optimal. The insertion operator uses
<a name="an1368"></a>
<em>accessor</em> members which can be implemented as inline members,
effectively making the private data members directly available for
inspection. The extraction operator requires the use of <a name="an1369"></a>
<em>modifier</em> members
that could hardly be implemented differently: the old memory will always have
to be deleted, and the new value will always have to be copied to newly
allocated memory.
<p>
But let's once more take a look at the class <code>PersonData</code>, introduced in
section <a href="cplusplus09.html#EXPLICIT">9.4</a>. It seems likely that this class has at least the
following (private) data members:
        <pre>
    class PersonData
    {
        Person *d_person;
        size_t d_n;
    };
</pre>
    When constructing an overloaded insertion operator for a <code>PersonData</code>
object, e.g., inserting the information of all its persons
into a stream, the overloaded insertion operator is implemented rather
inefficiently when the individual persons must be accessed using the
    <a name="an1370"></a>
index operator.
<p>
In cases like these, where the <a name="an1371"></a>
accessor and <a name="an1372"></a>
modifier members tend to
become rather complex, direct access to the private data members might improve
efficiency. So, in the context of insertion and extraction, we are looking for
overloaded member functions implementing the insertion and extraction
operations and having access to the private data members of the objects to be
inserted or extracted. In order to implement such functions <em>non-member</em>
functions must be given access to the private data members of a class. The
<a name="an1373"></a>
<code>friend</code> keyword is used to realize this.
<p>
<a name="FriendsFriendfun"></a><a name="l170"></a>
<h2>11.1: Friend functions</h2>
    <a name="friends/friendfun"></a>    Concentrating on the <code>PersonData</code> class, our initial implementation of
the insertion operator is:
        <pre>
    ostream &amp;operator&lt;&lt;(ostream &amp;str, PersonData const &amp;pd)
    {
        for (size_t idx = 0; idx &lt; pd.nPersons(); idx++)
            str &lt;&lt; pd[idx] &lt;&lt; endl;
    }
</pre>
    This implementation will perform its task as expected: using the
(overloaded) insertion operator of the class <code>Person</code>, the information about
every <code>Person</code> stored in the <code>PersonData</code> object will be written on a
separate line.
<p>
However, repeatedly calling the <a name="an1374"></a>
index operator might reduce the
efficiency of the implementation. Instead, directly using the array <code>Person
*d_person</code> might improve the efficiency of the above function.
<p>
At this point we should ask ourselves if we consider the above <code>operator</code><<<code>()</code>
primarily an extension of the globally available <code>operator</code><<<code>()</code> function, or in
fact a member function of the class <code>PersonData</code>. Stated otherwise: assume
we would be able to make <code>operator</code><<<code>()</code> into a true member function of the class
<code>PersonData</code>, would we object? Probably not, as the function's task is very
closely tied to the class <code>PersonData</code>. In that case, the function can
sensibly be made a <a name="an1375"></a>
<em>friend</em> of the class <code>PersonData</code>, thereby allowing
the function access to the private data members of the class <code>PersonData</code>.
<p>
Friend functions must be declared as friends in the class interface. These
<a name="an1376"></a>
<em>friend declarations</em> refer neither to <code>private</code> nor to <code>public</code>
functions, so the friend declaration may be placed anywhere in the
class interface. Convention dictates that friend declaractions are listed
directly at the top of the class interface. So, for the class <code>PersonData</code>
we get:
        <pre>
    class PersonData
    {
        friend ostream &amp;operator&lt;&lt;(ostream &amp;stream, PersonData &amp;pd);
        friend istream &amp;operator&gt;&gt;(istream &amp;stream, PersonData &amp;pd);

        public:
            // rest of the interface
    };
</pre>
    The implementation of the insertion operator can now be altered so as to
allow the insertion operator direct access to the private data members of
the provided <code>PersonData</code> object:
        <pre>
    ostream &amp;operator&lt;&lt;(ostream &amp;str, PersonData const &amp;pd)
    {
        for (size_t idx = 0; idx &lt; pd.d_n; idx++)
            str &lt;&lt; pd.d_person[idx] &lt;&lt; endl;
    }
</pre>
    Once again, whether <code>friend</code> functions are considered acceptable or not
remains a matter of taste: if the function is in fact considered a member
function, but it cannot be defined as a member function due to the nature of
the <strong>C++</strong> grammar, then it is defensible to use the <code>friend</code> keyword. In
other cases, the <code>friend</code> keyword should rather be avoided, thereby
respecting the principles of <a name="an1377"></a>
<em>encapsulation</em> and <a name="an1378"></a>
<em>data hiding</em>.
<p>
Explicitly note that if we want to be able to insert <code>PersonData</code>
objects into <code>ostream</code> objects without using the <code>friend</code> keyword, the
insertion operator cannot be placed inside the
<code>PersonData</code> class. In this case <code>operator</code><<<code>()</code> is a normal
overloaded variant of the insertion operator, which must therefore
be  declared and defined outside of the <code>PersonData</code> class. This situation
applies, e.g., to the example at the beginning of this section.
<p>
<a name="l171"></a>
<h2>11.2: Inline friends</h2>
    <a name="friends/inline"></a>In the previous section we stated that <code>friends</code> can be considered
    <a name="an1379"></a>
member functions of a class, albeit that the characteristics of the
function prevents us from actually defining the function as a member
function. In this section we will extend this line of reasoning a little
further.
<p>
If we conceptually consider friend functions to be member functions, we should
be able to design a true member function that performs the same tasks as our
<code>friend</code> function. For example, we could construct a function that inserts a
<code>PersonData</code> object into an <code>ostream</code>:
        <pre>
    ostream &amp;PersonData::insertor(ostream &amp;str) const
    {
        for (size_t idx = 0; idx &lt; d_n; idx++)
            str &lt;&lt; d_person[idx] &lt;&lt; endl;
        return str;
    }
</pre>
    This member function can be used by a <code>PersonData</code> object to insert
that object into the <code>ostream str</code>:
        <pre>
    PersonData pd;

    cout &lt;&lt; "The Person-information in the PersonData object is:\n";
    pd.insertor(str);
    cout &lt;&lt; "========\n";
</pre>
    Realizing that <code>insertor()</code> does the same thing as the overloaded
insertion operator, earlier defined as a <code>friend</code>, we could simply call the
<code>insertor()</code> member in the code of the <code>friend</code> <code>operator</code><<<code>()</code> function. Now
this <code>operator</code><<<code>()</code> function needs <em>only one statement</em>: it calls
<code>insertor()</code>. Consequently:
    <ul>
    <li> The <code>insertor()</code> function may be hidden in the class by making it
<code>private</code>, as there is not need for it to be called elsewhere
    <li> The <code>operator</code><<<code>()</code> may be constructed as <em>inline</em> member, as it
contains but one statement. However, this is deprecated since it contaminates
class interfaces with implementations. The overloaded <code>operator</code><<<code>()</code> member should
be implemented below the class interface:
    </ul>
    Thus, the relevant section of the class interface of <code>PersonData</code>
becomes:
        <pre>
    class PersonData
    {
        friend ostream &amp;operator&lt;&lt;(ostream &amp;str, PersonData const &amp;pd);

        private:
            ostream &amp;insertor(ostream &amp;str) const;
    };

    inline std::ostream &amp;operator&lt;&lt;(std::ostream &amp;str, PersonData const &amp;pd)
    {
        return pd.insertor(str);
    }
</pre>
    The above example illustrates the final step in the development of
<code>friend</code> functions. It allows us to formulate the following principle:
    <blockquote>
    Although <code>friend</code> functions have access to private members of a
class, this characteristic should not be used indiscriminately, as it results
in a severe breach of the principle of <a name="an1380"></a>
encapsulation, thereby making
non-class functions dependent on the implementation of the data in a class.
<p>
Instead, if the task a <code>friend</code> function performs, can be implemented by
a true member function, it can be argued that a <code>friend</code> is merely a
syntactical synonym or alias for this member function.
<p>
The interpretation of a  <a name="an1381"></a>

<code>friend</code> function as a synonym for a member function is made concrete by
constructing the <code>friend</code> function as an <a name="an1382"></a>
<em>inline</em> function.
<p>
As a principle we therefore state that <code>friend</code> functions should be
avoided, unless they can be constructed as inline functions, having only one
statement, in which an appropriate private member function is called.
    </blockquote>
    Using this principle, we ascertain that all code that has access to the
private data of a class remains confined to the class itself. This even holds
true for <code>friend</code> functions, as they are defined as simple inline functions.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus10.html">Previous Chapter</a>
    <li> <a href="cplusplus12.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
